﻿package com.agileai.miscdp.hotweb.generator.query;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;

import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.database.SqlBuilder;
import com.agileai.miscdp.hotweb.domain.query.QueryFuncModel;
import com.agileai.miscdp.hotweb.domain.query.QuerySQLMapModel;
import com.agileai.miscdp.hotweb.generator.Generator;
import com.agileai.miscdp.util.MiscdpUtil;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
/**
 * SQLMap文件代码生成器
 */
public class QMSqlMapGenerator implements Generator{
	private String sqlMapFile = null;
    private String findRecordsSql = null;
    private QueryFuncModel funcModel = null;
    private String[] rsIds = null;
    private String templateDir = null;
    private QuerySQLMapModel querySQLMapModel = null;
    
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void generate() {
		try {
			this.initModel();
			String fileName = "template";
			try {
				templateDir = FileLocator.toFileURL(Platform.getBundle(MiscdpPlugin.getPluginId()).getResource(fileName)).getFile().toString();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Configuration cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(templateDir+"/query"));
	        cfg.setObjectWrapper(new DefaultObjectWrapper());
	        Template temp = cfg.getTemplate("SqlMap.xml.ftl");
	        Map root = new HashMap();
	        root.put("table",this.querySQLMapModel);
	        FileWriter out = new FileWriter(new File(this.sqlMapFile)); 
//	        Writer out = new OutputStreamWriter(System.out);
	        temp.process(root, out);
	        out.flush();		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void initModel(){
		this.querySQLMapModel = new QuerySQLMapModel();
		querySQLMapModel.setNamespace(funcModel.getSqlNameSpace());
		String listSQL = MiscdpUtil.getProcessedConditionSQL(findRecordsSql);
		querySQLMapModel.setQueryRecordsSQL(listSQL);
		SqlBuilder sqlBuilder = new SqlBuilder();
		String findDetailSQL = sqlBuilder.parseFindDetailSql(findRecordsSql, rsIds);;
		querySQLMapModel.setFindDetailSQL(findDetailSQL);
	}
	public void setSqlMapFile(String sqlMapFile) {
		this.sqlMapFile = sqlMapFile;
	}
	public void setFindRecordsSql(String findRecordsSql) {
		this.findRecordsSql = findRecordsSql;
	}
	public void setRsIds(String[] rsIds) {
		this.rsIds = rsIds;
	}
	public void setFuncModel(QueryFuncModel funcModel) {
		this.funcModel = funcModel;
	}
}
